package com.heima.behavior.service.impl;


import com.alibaba.fastjson.JSON;
import com.heima.behavior.common.BehaviorConstants;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.UpdateArticleMess;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
	@Autowired
	private CacheService cacheService;
	@Autowired
	private KafkaTemplate kafkaTemplate;
	
	@Override
	public ResponseResult likeBehavior(LikesBehaviorDto dto) {
		//参数合法性判断
		if (dto == null) {
			return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
		}
		//用户登录状态判断
		ApUser currentUser = AppThreadLocalUtil.getUser();
		Integer currentUserId = currentUser.getId();
		if (currentUser == null || currentUserId == null) {
			return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
		}
		
		//需要参数提取
		Long articleId = dto.getArticleId();
		Short operation = dto.getOperation();
		Short type = dto.getType();
		
		//行为判断
		if (operation == 0) {
			//点赞
			UpdateArticleMess updateArticleMess = new UpdateArticleMess();
			updateArticleMess.setAdd(1);
			updateArticleMess.setArticleId(articleId);
			updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
			kafkaTemplate.send("itcast-topic-in", JSON.toJSONString(updateArticleMess));
			
			//获取缓存中是否存在有数据
			Object o = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleId.toString(), currentUserId.toString());
			if (o != null) {
				return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "请慢一点");
			}
			cacheService.hPut(BehaviorConstants.LIKE_BEHAVIOR + articleId, currentUserId.toString(), JSON.toJSONString(dto));
			

		} else if (operation == 1) {
			//取消点赞
			cacheService.hDelete(BehaviorConstants.LIKE_BEHAVIOR + articleId, currentUserId.toString());
			
			UpdateArticleMess updateArticleMess = new UpdateArticleMess();
			updateArticleMess.setAdd(-1);
			updateArticleMess.setArticleId(articleId);
			updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
			kafkaTemplate.send("itcast-topic-in", JSON.toJSONString(updateArticleMess));
		}
		
		//返回结果
		return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
	}
}
